$(document).ready(function () {

    initSubMenu();
    queryTable();

    layui.use(function () {

        var layer = layui.layer;

        // 表格
        form = layui.form;
        form.on('select(status)', function (data) {//监听状态
            $('div[lay-filter="search"]').click();
        });
        form.on('select(taskType)', function (data) {//监听周期
            $('div[lay-filter="search"]').click();
        });
        form.on('select(commandType)', function (data) {//监听操作
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable();
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            var selectArr = xmSel.getValue();
            var devices = selectArr.reduce((acc, item) => {
                acc.push(
                    {
                        "deviceId": item.id,
                        "nodeId": item.nodeId
                    }
                );
                return acc;
            }, []);



            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            var time = data.field.time.split(':')
            data.field.hour = time[0]
            data.field.minute = time[1]
            data.field.second = time[2]


            data.field.devices = devices;
            new AjaxChain()
                .setUrl('/task/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });


    });
})
var params = {};//查询条件参数
var form, unit;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID

//查询物资类型列表
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/task/info/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'taskName', title: '任务名称', align: "center" }
                , { field: 'taskTypeDesc', title: '周期类型', align: "center" }
                , { field: 'commandTypeDesc', title: '操作类型', align: "center" }
                , {
                    title: '操作时间', align: "center",
                    templet: function (d) {

                        if (d.taskType == 1) {//每天
                            return d.hour + '点' + d.minute + '分' + d.second + '秒'

                        } else {
                            var weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

                            return (d.dayOfWeek >= 0 && d.dayOfWeek) ? weekdays[d.dayOfWeek] : ''
                        }

                    },
                }
                , {
                    title: '状态', align: "center",
                    templet: '#ID-table-templet-switch'
                }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                <div onclick='tableHandle(1,${res})' class="table-edit layui-btn">
                                  <img src="../static/img/edit.png">编辑
                                </div>
                                <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                                  <img src="../static/img/del.png">删除
                                </div>
                              </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

        layui.form.on('switch(templet-status)', function (obj) {

            var id = this.value;

            var name = this.name;
            new AjaxChain()
                .setUrl('/task/' + (obj.elem.checked ? 'start' : 'stop'))
                .setData({ taskId: id })
                .then(data => {
                    layer.msg('操作成功', { icon: 1, time: 1500 });
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/task/delete')
                    .setData({ taskId: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + '任务',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['40%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {

            layui.laydate.render({
                elem: '#laydate-time',
                type: 'time',
                format: 'H:m:s'
            });


            if (res) {
                queryNodes(res.id)
                res.time=res.hour+':'+res.minute+':'+res.second
                if(res.taskType==2){
                    $('#item-dayOfWeek').show()
                }

                form.val('editForm', res);

            } else {
                queryNodes()
                form.render(null, 'editForm');
            }

            form.on('select(taskTypeEdit)', function (data) {//监听状态


                if (data.value == 1) {
                    $('#item-dayOfWeek').hide()
                } else if (data.value == 2) {
                    $('#item-dayOfWeek').show()
                } else {
                    $('#item-dayOfWeek').hide()
                }

            });


        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                    <div class="form-item">
                        <label class="layui-form-label">任务名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="taskName" lay-affix="clear" placeholder="请输入" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">节点绑定</label>
                        <div class="layui-input-block">
                            <div id="devices" class="xm-select-demo"></div>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">命令类型</label>
                        <div class="layui-input-block">
                            <select name="commandType" lay-filter="" lay-verify="required">
                                <option value="">请选择命令类型</option>
                                <option value="6">分闸</option>
                                <option value="7">合闸</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">任务类型</label>
                        <div class="layui-input-block">
                            <select name="taskType" lay-filter="taskTypeEdit" lay-verify="required">
                                <option value="">请选择周期类型</option>
                                <option value=1>每天</option>
                                <option value=2>每周</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-item" id="item-dayOfWeek" style="display:none;">
                        <label class="layui-form-label">执行日期</label>
                        <div class="layui-input-block">
                            <select name="dayOfWeek" lay-filter="" >
                                <option value="">请选择执行日期</option>
                                <option value="1">周一</option>
                                <option value="2">周二</option>
                                <option value="3">周三</option>
                                <option value="4">周四</option>
                                <option value="5">周五</option>
                                <option value="6">周六</option>
                                <option value="7">周日</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">执行时间</label>
                        <div class="layui-input-block">
                            <input type="text" name="time" id="laydate-time" lay-affix="clear" placeholder="请输入"
                                class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                        <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                    </div>
                </form>`
    });

}


var xmSel = null
queryNodes = (taskId) => {

    new AjaxChain()
        .setUrl('/device/electric/node/list/all')
        .then(data => {

            xmSel = xmSelect.render({
                el: '#devices',
                template({ item, sels, name, value }) {
                    return item.nodeName + '（' + item.nodeNum + '）' + '<span style="position: absolute; right: 10px; color: #8799a3">' + item.name + '</span>'
                },
                searchTips: '输入节点名称查询',
                filterable: true,
                prop: {
                    name: 'nodeName',
                    value: 'nodeId',
                },
                data: data
            })


            if (taskId) {
                new AjaxChain()
                    .setUrl('/task/device/list?taskId=' + taskId)
                    .then(data => {
                        console.log(data);
                        var d = data.map(item => item.nodeId);
                        xmSel.setValue(d)

                    })
                    .send();
            }

        })
        .send();
}